package cn.jiyun.service.impl;

import cn.jiyun.dao.TeacherDao;
import cn.jiyun.entity.PageResult;
import cn.jiyun.entity.QueryPageBean;
import cn.jiyun.pojo.Role;
import cn.jiyun.pojo.Teacher;
import cn.jiyun.pojo.User;
import cn.jiyun.service.TeacherService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Teacher> page = teacherDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Teacher teacher) {
        teacherDao.add(teacher);
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.hset("teacher",teacher.getId()+"", JSONObject.toJSONString(teacher));
    }

    @Override
    public void edit(Teacher teacher) {
        teacherDao.updateByPrimaryKeySelective(teacher);
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.hset("teacher",teacher.getId()+"", JSONObject.toJSONString(teacher));
    }

    @Override
    public void delete(Integer id) {

        Integer count = teacherDao.findByTid(id);

        if (count==0){
            Jedis jedis = new Jedis("127.0.0.1",6379);
            Teacher teacher = teacherDao.selectByPrimaryKey(id);
            jedis.hdel("teacher",teacher.getId()+"");
            teacherDao.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<Teacher> findAll() {
        return teacherDao.selectAll();
    }

    @Override
    public User findByUserName(String username) {
        return teacherDao.findByUserName(username);
    }

    @Override
    public List<Role> findByUid(Integer id) {
        return teacherDao.findByUid(id);
    }
}
